package com.masterclient.app.businessmodule.usermodule.login;

import android.graphics.Typeface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.fragment.FCBaseFragment;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.baselibrary.utils.StringsUtils;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.eoner.middlelib.eventbus.event.LoginSuccessEvent;
import com.masterclient.app.R;
import com.masterclient.app.businessmodule.usermodule.login.contract.ForgetPwdContract;
import com.masterclient.app.businessmodule.usermodule.login.contract.ForgetPwdPresenter;
import com.masterclient.app.utils.CaptchaUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者：Hxm
 * 创建时间：2019/12/17
 * 功能说明：
 */
@Route(path = AroutePath.FORGET_PED_FRAGMENT)
public class ForgetPwdFragment extends FCBaseFragment<ForgetPwdPresenter> implements ForgetPwdContract.View {

    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_verify)
    TextView tvVerify;
    @Autowired(name = "mobile")
    String mobile;

    private SPUtils spUtils;
    private CaptchaUtil captchaUtil;
    private String phoneNum;
    private CountDownTimer timer1,timer2;

    public static ForgetPwdFragment newInstance(){
        return new ForgetPwdFragment();
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Override
    protected int requireGetLayoutId() {
        return R.layout.fragment_forget_pwd;
    }

    @Override
    protected void requireSetCustomNavigationBar(FCNavigationBar navigationBar) {
        navigationBar.setLineHidden(true);
    }

    @Override
    protected void requireInitUIAndData(Bundle savedInstanceState) {

        etPhone.requestFocus();
        spUtils = SPUtils.getInstance();
        showSoftInput(etPhone);
        initEtHint(etPhone,"请输入手机号码",13);
        if (mobile != null && mobile.length() > 0) {
            etPhone.setText(mobile);
        }
//        etPhone.setText(spUtils.getString(Config.FORGET_PWD_PHONE));
        tvVerify.setClickable(false);
        tvVerify.setBackgroundResource(R.drawable.login_unable_click_bkg);
//        timer1 = new CountDownTimer((60 * 1000) - (System.currentTimeMillis()), 1000) {
//            @Override
//            public void onTick(long millisUntilFinished) {
//                tvVerify.setText(millisUntilFinished / 1000 + "s");
//            }
//
//            @Override
//            public void onFinish() {
//                tvVerify.setClickable(true);
//                tvVerify.setBackgroundResource(R.drawable.login_able_click_bkg);
//                tvVerify.setText("获取验证码");
//
//                etPhone.setFocusableInTouchMode(true);
//
//                etPhone.setFocusable(true);
//
//                etPhone.requestFocus();
//            }
//        };
//        timer1.start();

        tvVerify.setClickable(false);
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if (charSequence == null || charSequence.length() == 0) {
                    etPhone.setTypeface(Typeface.DEFAULT);
                    return;
                }
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < charSequence.length(); i++) {
                    if (i != 3 && i != 8 && charSequence.charAt(i) == ' ') {
                        continue;
                    } else {
                        sb.append(charSequence.charAt(i));
                        if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != ' ') {
                            sb.insert(sb.length() - 1, ' ');
                        }
                    }
                }
                if (!sb.toString().equals(charSequence.toString())) {
                    int index = start + 1;
                    if (sb.charAt(start) == ' ') {
                        if (before == 0) {
                            index++;
                        } else {
                            index--;
                        }
                    } else {
                        if (before == 1) {
                            index--;
                        }
                    }
                    etPhone.setText(sb.toString());
                    etPhone.setSelection(index);
                }

                if (etPhone.getText().toString().length() > 0) {
                    Utils.setDin(etPhone, getContext());
                } else {
                    etPhone.setTypeface(Typeface.DEFAULT);
                }

                if(etPhone.getText().toString().trim().replace(" ","").length()==11){
                    tvVerify.setClickable(true);
                    tvVerify.setBackgroundResource(R.drawable.login_able_click_bkg);
                    tvVerify.setTextColor(0xffffffff);
                }else {
                    tvVerify.setClickable(false);
                    tvVerify.setBackgroundResource(R.drawable.login_unable_click_bkg);
                    tvVerify.setTextColor(0xffffffff);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        String mobile = getArguments().getString("mobile");
        if(!TextUtils.isEmpty(mobile)){
            etPhone.setText(mobile);
            etPhone.setSelection(etPhone.getText().toString().length());
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        captchaUtil = new CaptchaUtil(getContext(), "忘记密码");
        captchaUtil.setCaptchaListerner(new CaptchaUtil.CaptchaListerner() {
            @Override
            public void onSuccess(String ne) {
                mPresenter.getCaptcha(phoneNum,"forget_password",ne);
                tvVerify.setClickable(false);
            }

            @Override
            public void onFailed() {
tvVerify.setClickable(true);
            }
        });
    }

    //TODO:通知登录成功
    /**
     * 登录成功刷新
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loginSuccessEvent(LoginSuccessEvent event) {
        if (getActivity() != null) {
            getActivity().finish();
        }
    }

    @Override
    public void onDestroy() {
        if(timer1!=null){
            timer1.cancel();
        }
        if((timer2!=null)){
            timer2.cancel();
        }
        super.onDestroy();
    }

    @OnClick({R.id.tv_verify})
    void onClick(View view){
        switch (view.getId()){
            case R.id.tv_verify:
                //可直接调用验证函数Validate()，本demo采取在异步任务中调用（见UserLoginTask类中）
                //mCaptcha.Validate();
                phoneNum = etPhone.getText().toString().trim().replace(" ","");
                if(StringsUtils.isPhoneNum(phoneNum)){
                    if(SystemConfigStorage.getInstance().isOpenSlipPageCode()) {
                        if (CaptchaUtil.CAPTCHA_NUMBER_TIMES >= Config.CAPTCHA_MAX_TIMES){
                            mPresenter.getCaptcha(phoneNum,"forget_password","");
                        }else {
                            captchaUtil.start();
                        }
                    }else {
                        mPresenter.getCaptcha(phoneNum,"forget_password","");
                        tvVerify.setClickable(false);
                    }
                } else {
                    showToast("请输入正确的手机号");
                }
                break;
        }
    }

    @Override
    public void getCaptchaResult(String result) {
        if(Boolean.valueOf(result)){
            //获取验证码成功
            spUtils.put(Config.FORGET_PWD_VERIFY_TIME,System.currentTimeMillis());
            spUtils.put(Config.FORGET_PWD_PHONE,etPhone.getText().toString().trim());
//            tvVerify.setBackgroundResource(R.drawable.login_unable_click_bkg);

//            etPhone.setFocusable(false);
//            etPhone.setFocusableInTouchMode(false);
            tvVerify.setClickable(true);
            ARouter.getInstance().build(AroutePath.LOGIN_CODE_LOGIN).withString("phone",phoneNum).withString("from","forgetPwdPage").navigation();
        }else {
            showToast("获取验证码失败，请重试");
            tvVerify.setClickable(true);
            tvVerify.setBackgroundResource(R.drawable.login_able_click_bkg);
            tvVerify.setText("获取验证码");
        }
    }

    @Override
    public void showError(String msg) {
        if(tvVerify != null){
            tvVerify.setClickable(true);
        }
        showToast(msg);
    }

}
